package com.pajx.testopengles.util

import android.content.Context
import android.opengl.GLES20
import android.util.Log
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.nio.charset.StandardCharsets

/**
 *User: RandBII
 *Date: 2020/8/11
 *Description: (方法移交给 GLHelper)
 *
 */
object ShaderHelper {

    fun loadShader(type: Int, shaderCode: String): Int {
        val shaderInt = GLES20.glCreateShader(type)
        GLES20.glShaderSource(shaderInt, shaderCode)
        GLES20.glCompileShader(shaderInt)
        checkShaderCompile(type, shaderInt)
        return shaderInt
    }


    fun loadShaderAsserts(context: Context, name: String): String {

        var input: InputStream? = null
        var bos: ByteArrayOutputStream? = null
        var buffer: ByteArray? = null
        try {
            input = context.resources.assets.open(name)
            bos = ByteArrayOutputStream()
            var aa: Int = 0
            while (input.read().also { aa = it } != -1) {
                bos.write(aa)
            }

            buffer = bos.toByteArray()
            return String(buffer, StandardCharsets.UTF_8).also {
                it.replace("\\r\\n", "\n")
            }


        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        } finally {
            input?.close()
            bos?.close()

        }

    }


    private fun checkShaderCompile(type: Int, shaderId: Int): Int {

        val status = IntArray(1)

        GLES20.glGetShaderiv(shaderId, GLES20.GL_SHADER_COMPILER, status, 0)
        if (status[0] == 0) {
            Log.e("-->", "shaderCompileInfo--> ${GLES20.glGetShaderInfoLog(shaderId)}")
            return 0
        }

        return shaderId
    }


    fun validateProgram(program: Int) {
        GLES20.glValidateProgram(program)
        val validateStatus: IntArray = IntArray(1)
        GLES20.glGetProgramiv(program, GLES20.GL_VALIDATE_STATUS, validateStatus, 0)
        Log.e(
            "-->", "programvalidate== ${validateStatus[0]}"
        )
        if (validateStatus[0] == GLES20.GL_FALSE) {
            Log.e(
                "-->",
                "program validate-->status =${validateStatus[0]}  info=  ${GLES20.glGetProgramInfoLog(
                    program
                )}"
            )
            GLES20.glDeleteProgram(program)
        }


    }

}